/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snmpapplication.snmp;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import snmpapplication.Main;
import snmpapplication.log.Severity;

/**
 *
 * @author APetcu
 */
public class SnmpClientGet {

    public static String snmpGet(String host, String community, String strOID) {
        String strResponse = "";
        ResponseEvent response;
        Snmp snmp;
        try {
            OctetString community1 = new OctetString(community);
            host = host + "/" + "161";
            Address tHost = new UdpAddress(host);
            TransportMapping transport = new DefaultUdpTransportMapping();
            transport.listen();
            CommunityTarget comtarget = new CommunityTarget();
            comtarget.setCommunity(community1);
            comtarget.setVersion(SnmpConstants.version1);
            comtarget.setAddress(tHost);
            comtarget.setRetries(2);
            comtarget.setTimeout(3000);
            PDU pdu = new PDU();
            pdu.add(new VariableBinding(new OID(strOID)));
            pdu.setType(PDU.GET);
            snmp = new Snmp(transport);
            response = snmp.get(pdu, comtarget);
            if (response != null) {
                if (response.getResponse() == null) {
                    Main.log.log(new Severity(Severity.SEV_HIG), "NULL response from host");
                    return null;
                }
                if (response.getResponse().getErrorStatusText().equalsIgnoreCase("Success")) {
                    PDU pduresponse = response.getResponse();
                    strResponse = pduresponse.getVariableBindings().firstElement().toString();
                    if (strResponse.contains("=")) {
                        int len = strResponse.indexOf("=");
                        strResponse = strResponse.substring(len + 1, strResponse.length());
                    }
                }
            } else {
                Main.log.log(new Severity(Severity.SEV_MED), "Timeout occured during SNMP GET");
            }
            snmp.close();
        } catch (Exception e) {
            Main.log.log(new Severity(Severity.SEV_ERR), "Exception during SNMP GET:" + e.getMessage());
            return null;
        }

        return strResponse;
    }
}
